//
//  SendPingLunViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/5/12.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "SendPingLunViewController.h"
#import "AFNetworking.h"

#define kCurrentUserToken @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cLzEyMC4yNi4xMjkuODRcL2FwaVwvdXNlclwvb3BlbnNpZ25pbiIsImlhdCI6MTQ2NTcxNTUwOSwiZXhwIjoxNDY4MzA3NTA5LCJuYmYiOjE0NjU3MTU1MDksImp0aSI6IjNhMjBkOGE0NzA4ZjcwMzIxMWRkNTY2NzJhYzY1M2EwIn0.p5XetTw0DOnpd4Iz7otwzsCRyPA0mPGy-ERhnAFrOF8"

@interface SendPingLunViewController ()<UITextViewDelegate>

@property (nonatomic, strong) UIButton *sendPingLunButton; // 发送按钮

@property (nonatomic, strong) UITextView *pingLunTV; // 评论的textView

@end

@implementation SendPingLunViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    // 布局
    [self addMySubview];
}

// navi的修改
- (void)changeNavigation
{
    self.navigationItem.title = @"写评论";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    UIBarButtonItem *fanHuiBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
    UILabel *cancelLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 23)];
    cancelLable.text = @"取消";
    cancelLable.textAlignment = NSTextAlignmentLeft;
    cancelLable.font = [UIFont fontWithName:@"'Arial-BoldMT" size:k16Big];
    cancelLable.textColor = [UIColor whiteColor];
    UIBarButtonItem *leftCanCelBarItem = [[UIBarButtonItem alloc] initWithCustomView:cancelLable];
    self.navigationItem.leftBarButtonItems = @[fanHuiBarItem, leftCanCelBarItem];
    
    // 右方
    self.sendPingLunButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.sendPingLunButton.frame = CGRectMake(0, 0, 50, 23);
    [self.sendPingLunButton setTitle:@"发送" forState:UIControlStateNormal];
    [self.sendPingLunButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.sendPingLunButton addTarget:self action:@selector(sendPingLun:) forControlEvents:UIControlEventTouchUpInside];
    self.sendPingLunButton.titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:k16Big];
    self.sendPingLunButton.layer.borderWidth = 1 * kAdjustParamater;
    self.sendPingLunButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.sendPingLunButton.layer.cornerRadius = 6 * kAdjustParamater;
    self.sendPingLunButton.layer.masksToBounds = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.sendPingLunButton];
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 发送评论
- (void)sendPingLun:(UIButton *)button
{
    
  //  NSLog(@"发送评论");
    // 获取空格的数量
    NSInteger spaceCount = 0;
    // 判断回车键的数量
    NSInteger huiCheJianCount = 0;
    for (int i = 0; i < self.pingLunTV.text.length; i++) {
        NSString *tempS = [self.pingLunTV.text substringWithRange:NSMakeRange(i, 1)];
        if ([tempS isEqualToString:@" "]) {
            spaceCount++;
        }
        if ([tempS isEqualToString:@"\n"]) {
            huiCheJianCount++;
        }
    }
    
    
 //   NSLog(@"空格的数量：%ld", spaceCount);
    if (self.pingLunTV.text.length < 1 || self.pingLunTV.text.length > 50 || [self.pingLunTV.text isEqualToString:@"写评论..."]) {
        [self addAlertNoSuit:@"请输入1~50个字"];
    } else if (self.pingLunTV.text.length == spaceCount || self.pingLunTV.text.length == huiCheJianCount || self.pingLunTV.text.length == (spaceCount + huiCheJianCount)) {
        // 说明只输入空格了或者回车了
        [self addAlertNoSuit:@"请输入内容，不能只输入空格或换行符"];
       // [self addAlertNoSuit:@"请输入汉字|字母|数字|下划线"];
    } else {
        NSLog(@"可以发表");
        if ([self.isZiXunOrGuanFangActivity isEqualToString:@"ziXun"]) {
            // 开启动画
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
            NSString *urlString = [NSString stringWithFormat:@"http://120.26.129.84/api/news/comment?token=%@", kCurrentUserToken];
            NSDictionary *paramaterDic = @{@"news_id":self.ziXunID, @"content":self.pingLunTV.text};
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            [manager POST:urlString parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
                NSDictionary *statusDic = [responseObject valueForKey:@"status"];
                NSString *msgStrign = [statusDic valueForKey:@"msg"];
                if ([msgStrign isEqualToString:@"评论成功"]) {
                    ZiXunGeRenPingLunModel *model = [[ZiXunGeRenPingLunModel alloc] init];
                    self.addZiXun(model);
                    NSLog(@"评论成功");
                    [self PinglunChengGong];
                }
                //  取消键盘
                [self.pingLunTV resignFirstResponder];
                // 关闭动画
                [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                NSLog(@"error = %@", error);
                [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"发表失败，请重试" ToView:self];
                // 关闭动画
                [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
            }];
        } else if ([self.isZiXunOrGuanFangActivity isEqualToString:@"guanFangActivity"]) {
            NSLog(@"官方活动");
        }
       
    }
   
}



#pragma mark - 布局
- (void)addMySubview
{
    // 评论的背景
    UIView *pingLunBackGroundView = [[UIView alloc] initWithFrame:CGRectMake(15 * kAdjustParamater, 15 * kAdjustParamater, 345 * kAdjustParamater, 235 * kAdjustParamater)];
    pingLunBackGroundView.backgroundColor = [UIColor whiteColor];
    pingLunBackGroundView.layer.cornerRadius = 7 * kAdjustParamater;
    pingLunBackGroundView.layer.borderColor = [kCyanColor CGColor];
    pingLunBackGroundView.layer.borderWidth = 1 * kAdjustParamater;
    pingLunBackGroundView.layer.masksToBounds = YES;
    pingLunBackGroundView.userInteractionEnabled = YES;
    [self.view addSubview:pingLunBackGroundView];
    
    // 评论TV
    self.pingLunTV = [[UITextView alloc] initWithFrame:CGRectMake(12 * kAdjustParamater, 12 * kAdjustParamater, 321 * kAdjustParamater, 211 * kAdjustParamater)];
  //  self.pingLunTV.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    self.pingLunTV.font = [UIFont fontWithName:@"ArialMT" size:k16Big];
    self.pingLunTV.tintColor = kCyanColor;
    self.pingLunTV.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    self.pingLunTV.delegate = self;
    self.pingLunTV.text = @"写评论...";
    [pingLunBackGroundView addSubview:_pingLunTV];
    
    // 添加tv辅助视图
    // 构建辅助视图
    UIView *seorryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 25 * kAdjustParamater)];
    seorryView.backgroundColor = [UIColor colorWithRed:249 / 255.0 green:249 / 255.0 blue:249 / 255.0 alpha:1];
    
    UILabel *grayLineOnSeorryView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1 * kAdjustParamater)];
    grayLineOnSeorryView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    [seorryView addSubview:grayLineOnSeorryView];
    
    // 完成button
    UIButton *textViewFinishButton = [UIButton buttonWithType:UIButtonTypeSystem];
    textViewFinishButton.frame = CGRectMake(334  *kAdjustParamater, 5 * kAdjustParamater, 30 * kAdjustParamater, 15 * kAdjustParamater);
    textViewFinishButton.layer.cornerRadius = 2 * kAdjustParamater;
    [textViewFinishButton setTitle:@"完成" forState:UIControlStateNormal];
    [textViewFinishButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    textViewFinishButton.backgroundColor = kCyanColor;
    textViewFinishButton.titleLabel.font = [UIFont systemFontOfSize:k13Big];
    [textViewFinishButton addTarget:self action:@selector(tvFinish:) forControlEvents:UIControlEventTouchUpInside];
    [seorryView addSubview:textViewFinishButton];
    self.pingLunTV.inputAccessoryView = seorryView;

    
}

// 评论成功
- (void)PinglunChengGong
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"发表成功，您可以在评论列表查看" preferredStyle:UIAlertControllerStyleAlert];
    // 修改message
    NSMutableAttributedString *messageString = [[NSMutableAttributedString alloc] initWithString:@"发表成功，您可以在评论列表查看"];
    [messageString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, messageString.length)];
    [messageString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:k17Big] range:NSMakeRange(0, messageString.length)];
    [alertVC setValue:messageString forKey:@"attributedMessage"];
    [self presentViewController:alertVC animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
    });
}

#pragma mark - 提醒框
- (void)addAlertNoSuit:(NSString *)content
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提醒" message:content preferredStyle:UIAlertControllerStyleAlert];
    // 修改标题颜色
    NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"提醒"];
    [title addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
    [title addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
    [alertVC setValue:title forKey:@"attributedTitle"];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"确定");
    }];
    [alertVC addAction:sureAction];
    [self presentViewController:alertVC animated:YES completion:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    }];
    
}

#pragma mark - 正则表达式
- (BOOL)addZhengZe:(NSString *)string
{
    NSString *regex = @"^[a-zA-Z0-9\u4e00-\u9fa5,:_.“”:;、。]+$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
   textView.text = @"";
}

- (void)textViewDidChange:(UITextView *)textView
{
    NSLog(@"评论内容 = %@,评论内容的字符数量 = %ld", textView.text, textView.text.length);
    if (textView.text.length > 0) {
        [self.sendPingLunButton setTitleColor:kCyanColor forState:UIControlStateNormal];
        self.sendPingLunButton.backgroundColor = [UIColor whiteColor];
    } else {
        [self.sendPingLunButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.sendPingLunButton.backgroundColor = kCyanColor;
    }
}

#pragma mark - 回收键盘
- (void)tvFinish:(UIButton *)button
{
    NSLog(@"回收键盘");
    if (self.pingLunTV.text.length == 0) {
        self.pingLunTV.text = @"写评论...";
    }
    [self.pingLunTV resignFirstResponder];
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
